package com.store.app.scan;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.activity.CashierActivity;
import com.store.app.http.Stores;
import com.store.app.http.Submit;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.IDUtil;
import com.store.app.utils.MoneyUtil;
import com.store.app.zxing.Capture_ZxingActivity;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/3/8.
 */

//首页扫一扫页面
public class CaptureActivity extends Capture_ZxingActivity implements View.OnClickListener, IOnHttpListener {
    //会员资料获取失败
    private static final int MSG_GETMENBER_FAILED = 16;
    //扫一扫扫出情亲卡弹窗
    private static final int MSG_QINGQINGKA_SUCC = 13;
    //结算情亲卡时执行
    private static final int MSG_QINGQINGKA_MEMBER_SUCC = 0;
    //扣款成功
    private static final int MSG_KOUKUAN_SUCC = 14;
    //扣款失败
    private static final int MSG_KOUKUAN_FAILED = 9;
    //网络链接错误
    private static final int MSG_NETWORK_FAILED = 2;
    //礼券赠送成功
    private static final int MSG_LIQUAN_SUCC = 15;
    //收银记录失败
    private static final int MSG_LIQUAN_FAILED = 8;
    //重新开启扫一扫
    private static final int MSG_RE_SCAN = 99;
    private LinearLayout acknowledgement, gathering;
    private ImageView retreat;
    private TextView payee_amount;
    //来自哪个页面
    private String genre;
    //扫描的值
    private String card_numshu;
    //来自哪个页面  2为首页跳转过来的
    private int ifcashier = 0;
    private double money, number_of_credits;
    private int token;
    //执行订单支付
    private String cash_balance;
    private String member_id;
    private String error;
    private String nick_name;
    public static String product_id;
    JSONObject object;
    private TextView name, number, consumption, mistake, tv_title;
    String block_name, block_number;
    String voucher_balance;//礼券余额--现在改为显示金币余额
    String gold;//金币余额
    private Dialog mDownloadDialog;
    private Context context;
    private int donate = 0;
    private int achieve = 0;
    private int width, height;
    private boolean isopen = false;
    private Long tsLong;
    private PopupWindow popupWindow = null;
    private NetRequest netRequest;
    private TextView tvTitle;
    private Dialog dialog;
    String sktCode;


    String draw_code;
    String activity_id ;
    String consumer_id;
    String activity_type ;
    String process_id ;
    public Handler handler = new Handler() {
        @SuppressLint("NewApi")
        @Override
        public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
            super.handleMessage(msg);

            switch (msg.what) {
                case MSG_QINGQINGKA_MEMBER_SUCC:
                    //账户余额是否大于要扣的金额
                    Log.v("zyl", "账户是否大于要扣的金额");
                    if (Double.parseDouble(cash_balance) - money > 0) {

                        new consume(member_id, money).start();
                    } else {
                        dismissProgressDialog();
                        new Builder(CaptureActivity.this)
                                .setTitle("刷卡失败")
                                .setMessage("余额不足")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                    }
                                })
                                .show();
                    }
                    break;
                case 1:
                    CashierActivity.goodsListBeanList.clear();
                    CashierActivity.handler.sendEmptyMessage(1);
                    Log.v("zyl", "关闭页面");
                    Intent intent = new Intent(CaptureActivity.this, CashierActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                  intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); //加上之后B跳转到Main时候 会调用之前的Main,并且执行onNewIntent
                    startActivity(intent);
                    finish();
                    break;
                case MSG_NETWORK_FAILED:
                    dismissProgressDialog();
                    Toast.makeText(getApplicationContext(), "请检查本地网络！",
                            Toast.LENGTH_SHORT).show();
                    break;
                case 3:

                    try {
                        //条形码
                        //{ }
                        object = new JSONObject(card_numshu);
                        String type = object.getString("type");
                        if (type.equals("P")) {
                            gathering.setVisibility(View.VISIBLE);
                            Log.v("zyl", "object:" + object.toString());
                            new Trading_check(object).start();
                        }

                    } catch (JSONException e) {
                        Toast.makeText(CaptureActivity.this, "不支持扫描该条码！", Toast.LENGTH_SHORT).show();
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    break;
                case 4:
                    gathering.setVisibility(View.GONE);
                    Toast.makeText(getApplicationContext(), error,
                            Toast.LENGTH_SHORT).show();
                    break;
                //支付接口(没有5)
                case 5:
                    new proceeds(object).start();
                    break;
                case 6:
                    Toast.makeText(getApplicationContext(), "成功",
                            Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case 7:
                    Builder builder = new Builder(CaptureActivity.this);
                    builder.setTitle(R.string.soft_title);
                    final LayoutInflater inflater = LayoutInflater.from(CaptureActivity.this);
                    View v = inflater.inflate(R.layout.reminder, null);
                    name = (TextView) v.findViewById(R.id.name);
                    name.setText(block_name);
                    number = (TextView) v.findViewById(R.id.number);
                    number.setText(block_number);
                    consumption = (TextView) v.findViewById(R.id.consumption);
                    consumption.setText(money + "");
                    builder.setView(v);
                    builder.setNegativeButton(R.string.soft_close, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
//								Intent intent7 = new Intent();
//								intent7.setClass(CaptureActivity.this,AddmerchandiseActivity.class);
//								startActivity(intent7);
                            CashierActivity.goodsListBeanList.clear();
                            CashierActivity.handler.sendEmptyMessage(1);
                            finish();
                        }
                    });
                    mDownloadDialog = builder.create();
                    mDownloadDialog.show();
                    break;

                case MSG_LIQUAN_FAILED:
                    dismissProgressDialog();
                    gathering.setVisibility(View.GONE);
                    handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 3000);
                    Toast.makeText(CaptureActivity.this, "收款失败：" + error, Toast.LENGTH_SHORT).show();
                    error = "";
                    break;
                //扣款失败。原因很多，可能是余额不足，也可能是对方账号有问题等
                case MSG_KOUKUAN_FAILED:
                    dismissProgressDialog();
                    Builder builder4 = new Builder(CaptureActivity.this);
                    //显示刷卡失败
                    builder4.setTitle(R.string.soft_titleone);
                    final LayoutInflater inflater4 = LayoutInflater.from(CaptureActivity.this);
                    View v4 = inflater4.inflate(R.layout.defeated, null);
                    mistake = (TextView) v4.findViewById(R.id.mistake);
                    //打印错误信息
                    mistake.setText(error);
                    builder4.setView(v4);
                    builder4.setNegativeButton(R.string.soft_close, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();
                        }
                    });
                    mDownloadDialog = builder4.create();
                    mDownloadDialog.show();
                    break;


                case 12:
                    gathering.setVisibility(View.VISIBLE);
                    try {
                        payee_amount.setText(object.get("amount") + "");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }//object.getString("money"));
                    Drawable drawable = getResources().getDrawable(R.drawable.border_scan);
                    acknowledgement.setBackground(drawable);
                    gathering.setClickable(true);
                    break;
                case MSG_QINGQINGKA_SUCC:
                    //从扫一扫页面扫亲情卡显示会员信息
                    Builder builder1 = new Builder(CaptureActivity.this);
                    builder1.setTitle(R.string.member_info);
                    final LayoutInflater inflater1 = LayoutInflater.from(CaptureActivity.this);
                    View v1 = inflater1.inflate(R.layout.member_information, null);
                    name = (TextView) v1.findViewById(R.id.name);
                    name.setText(nick_name);
                    number = (TextView) v1.findViewById(R.id.number);
                    number.setText(cash_balance);
                    consumption = (TextView) v1.findViewById(R.id.consumption);
                    consumption.setText(gold);
                    builder1.setView(v1);
                    builder1.setNegativeButton(R.string.soft_close, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            setReCapture();
                        }
                    });
                    mDownloadDialog = builder1.create();
                    mDownloadDialog.show();
                    break;
                case MSG_KOUKUAN_SUCC:


                    if (token != 0) {
                        Log.v("zyl", "总余额Stores.voucher_balanc：" + Stores.voucher_balance + "");
                        //必须总余额大于要扣的礼券数量才能执行
                        if (Stores.voucher_balance <= token) {
                            Toast.makeText(CaptureActivity.this, "礼券不足!", Toast.LENGTH_LONG).show();
                            token = 0;
                            show_failure(retreat);
                            dismissProgressDialog();
                        } else {
                            new Presented().start();
                        }
                    } else {
                        dismissProgressDialog();
                        donate = 1;
                    }
                    //收银记录
                    new commit_record().start();
                    break;
                //结算成功
                case MSG_LIQUAN_SUCC:
                    dismissProgressDialog();
                    if (donate == 1 && achieve == 1) {
                        isopen = true;
                        show_failure(retreat);
                    }
                    break;
                //会员资料获取失败
                case MSG_GETMENBER_FAILED:
                    Timer timer = new Timer();
                    TimerTask task = new TimerTask() {
                        public void run() {
                            setReCapture();
                            cancel();
                        }
                    };
                    timer.schedule(task, 2500);
                    dismissProgressDialog();
                    Toast.makeText(CaptureActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case MSG_RE_SCAN:
                    setReCapture();
                    break;
                //收款成功
                case 98:
                    Toast.makeText(getApplicationContext(), "收款成功", Toast.LENGTH_SHORT).show();
                    gathering.setVisibility(View.GONE);
                    setReCapture();
                    break;
                default:
                    break;
            }
        }
    };
    private LinearLayout ll_family_card;        //选中扫描亲情卡查询
    private LinearLayout ll_scan_pay;           //选中扫码支付
    private LinearLayout ll_member;           //选中扫会码
    private LinearLayout ll_validate_coupon;    //选中优惠券验证
    private final int STATE_FAMILY_CARD = 1;
    private final int STATE_SCAN_PAY = 2;
    private final int STATE_MEMEBER_PAY = 3;
    private final int STATE_VALIDATE_COUPON = 4;
    private final int STATE_DUIJIANGMA = 5;//兑奖码
    private int currentState = STATE_SCAN_PAY;//当前出于哪个状态
    private RelativeLayout rl_dialog_fail;
    private RelativeLayout rl_dialog_success;
    private TextView tv_fail_ok;
    private TextView tv_success_ok;
    private TextView tv_family_card;
    private TextView tv_member;
    private TextView tv_scan_pay;
    private TextView tv_validate_coupon;
    private ImageView img_family_card, img_scan_pay, img_validate_coupon, iv_member;
    private RelativeLayout rl_bottom_view;
    private TextView tv_dialog_success_content;
    private GoToLogin goToLogin;
    private TextView tv_phone;
    private TextView tv_banlce;
    private TextView tv_gold;
    private TextView tv_ban;
    private TextView tv_free;
    private TextView tv_Illegal;
    private TextView cancel;
    private TextView tv_thaw;
    private RelativeLayout rl_view;
    private String consumerId;
    private String cash_froze;
    private ImageView iv_duijiangma;
    private TextView tv_duijiangma;
    private LinearLayout ll_duijiangma;
    private TextView tv_luck_number;
    private TextView tv_get_reward;
    private TextView tv_duijiangma_ok;
    private RelativeLayout rl_duijiang_success;
    private TextView tv_duijiang_fail_why;
    private TextView tv_duijiang_fail_ok;
    private RelativeLayout rl_duijiang_dialog_fail;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_capture2);
        initView();
        netRequest = new NetRequest(this);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        WindowManager wm = this.getWindowManager();
        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();
        setInintView();
        findViewById();
        context = CaptureActivity.this;
        Intent intent = getIntent();
        genre = intent.getStringExtra("genre");
        rl_bottom_view.setVisibility(View.VISIBLE);
        if (genre.equals("function")) {
            ifcashier = 2;
            int width = LocationApplication.app.getDM().widthPixels;
            int high = LocationApplication.app.getDM().heightPixels;
            width = width / 8 * 3;
            high = high / 2 - width;
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.topMargin = high - MainActivity.dip2px(60);
            layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
            tv_title.setLayoutParams(layoutParams);
            tv_title.setText("将二维码放入框内,即可自动扫描");
        }

        goToLogin = new GoToLogin(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    private void findViewById() {
        payee_amount = (TextView) findViewById(R.id.payee_amount);
        acknowledgement = (LinearLayout) findViewById(R.id.acknowledgement);
        tv_title = (TextView) findViewById(R.id.cap_tv);
        retreat = (ImageView) findViewById(R.id.retreat);
        retreat.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                finish();
            }
        });
        //确认收款视图
        gathering = (LinearLayout) findViewById(R.id.gathering);
        gathering.setClickable(false);
        gathering.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                gathering.setClickable(false);
                acknowledgement.setBackgroundResource(R.drawable.border_scan_gray);
                new proceeds(object).start();
            }
        });
    }

    /**
     * 处理扫描结果
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(CaptureActivity.this, "扫描错误!", Toast.LENGTH_SHORT).show();
        } else {
            switch (ifcashier) {
                case 0:
                    card_numshu = resultString;
                    product_id = resultString;
                    break;
                case 1:
                    break;
                case 2:
                    Log.v("zyl", "进入查询");
                    card_numshu = resultString;
//                    String identifying = card_numshu.substring(0, 3);
//                    if (identifying.equals("MTH")) {
//                        //获取会员信息
//                        new access_member(card_numshu).start();
//
//                    } else if (identifying.equals("YHQ")) {
//
//
//                    } else {
//                        handler.sendEmptyMessage(3);
//                    }
                    if (currentState == STATE_FAMILY_CARD) {
                        if (card_numshu.length() > 3) {
                            String identifying = card_numshu.substring(0, 3);
                            if (identifying.equals("MTH")) {
                                //获取会员信息
                                new access_member(card_numshu).start();
                            } else {
                                handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 3000);
                                Toast.makeText(CaptureActivity.this, "此二维码非亲情卡！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } else if (currentState == STATE_SCAN_PAY) {
                        try {
                            //条形码
                            //{ }
                            object = new JSONObject(card_numshu);
                            String type = object.getString("type");
                            if (type.equals("P")) {

                                Log.v("zyl", "object:" + object.toString());
                                new Trading_check(object).start();
                            }
                        } catch (JSONException e) {
                            handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 3000);
                            Toast.makeText(CaptureActivity.this, "不支持扫描该条码！", Toast.LENGTH_SHORT).show();
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else if (currentState == STATE_VALIDATE_COUPON) {
                        if (card_numshu.length() > 3) {
                            String identifying = card_numshu.substring(0, 3);
                            if (identifying.equals("YHQ")) {
                                 sktCode = card_numshu.substring(3, card_numshu.length());
//                                netRequest.requestCouponValidate(1, sktCode);
                                Log.v("zyl", "YHQ---SKTCODE:" + sktCode);
                                netRequest.requestValidateFindForStores(2, sktCode);
                                handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 6000);
                            } else {
                                handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 3000);
                                Toast.makeText(CaptureActivity.this, "不支持扫描该条码！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } else if (currentState == STATE_MEMEBER_PAY) {
                        Log.v("zyl", "会员扫：" + card_numshu);
                        consumerId = card_numshu;
                        netRequest.requestUnfreeze_info(3, card_numshu);
                    } else if (currentState == STATE_DUIJIANGMA) {
                        Log.v("zyl", "兑奖码：" + card_numshu);
                        try {
                            JSONObject jsonObject = new JSONObject(resultString);
                             draw_code = jsonObject.getString("draw_code");
                             activity_id = jsonObject.getString("activity_id");
                             consumer_id = jsonObject.getString("consumer_id");
                             activity_type = jsonObject.getString("activity_type");
                             process_id = jsonObject.getString("process_id");
//                            if (!TextUtils.isEmpty(draw_code) && !TextUtils.isEmpty(activity_id) && !TextUtils.isEmpty(consumer_id)) {
//                                netRequest.requestValidateCode(7, MainActivity.member_id, activity_id, consumer_id, draw_code, activity_type, process_id);
//                            } else {
//                                Toast.makeText(CaptureActivity.this, "二维码信息不齐全", Toast.LENGTH_SHORT).show();
//                            }

                            if (!TextUtils.isEmpty(activity_type) && !TextUtils.isEmpty(MainActivity.member_id) && !TextUtils.isEmpty(activity_id) && !TextUtils.isEmpty(process_id) && !TextUtils.isEmpty(draw_code)) {
                                netRequest.requestValidateFind(9, activity_type, MainActivity.member_id, activity_id, process_id, draw_code);
                            } else {
                                Toast.makeText(CaptureActivity.this, "二维码信息不完整", Toast.LENGTH_SHORT).show();
                            }
                            handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 6000);
                        } catch (Exception e) {
                            handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 3000);
                            Toast.makeText(CaptureActivity.this, "不支持扫描该条码！", Toast.LENGTH_SHORT).show();
                        }
                    }


                    break;
                default:
                    break;
            }
        }
    }

    private void initView() {
        ll_family_card = (LinearLayout) findViewById(R.id.ll_family_card);
        ll_scan_pay = (LinearLayout) findViewById(R.id.ll_scan_pay);
        ll_member = (LinearLayout) findViewById(R.id.ll_member);
        ll_validate_coupon = (LinearLayout) findViewById(R.id.ll_validate_coupon);
        ll_family_card.setOnClickListener(this);
        ll_scan_pay.setOnClickListener(this);
        ll_member.setOnClickListener(this);
        ll_validate_coupon.setOnClickListener(this);

        rl_dialog_fail = (RelativeLayout) findViewById(R.id.rl_dialog_fail);
        rl_dialog_success = (RelativeLayout) findViewById(R.id.rl_dialog_success);
        tv_fail_ok = (TextView) findViewById(R.id.tv_fail_ok);
        tv_fail_ok.setOnClickListener(this);
        tv_success_ok = (TextView) findViewById(R.id.tv_success_ok);
        tv_success_ok.setOnClickListener(this);
        tv_family_card = (TextView) findViewById(R.id.tv_family_card);
        tv_member = (TextView) findViewById(R.id.tv_member);
        tv_scan_pay = (TextView) findViewById(R.id.tv_scan_pay);
        tv_validate_coupon = (TextView) findViewById(R.id.tv_validate_coupon);
        img_family_card = (ImageView) findViewById(R.id.img_family_card);
        iv_member = (ImageView) findViewById(R.id.iv_member);
        img_scan_pay = (ImageView) findViewById(R.id.img_scan_pay);
        img_validate_coupon = (ImageView) findViewById(R.id.img_validate_coupon);
        rl_bottom_view = (RelativeLayout) findViewById(R.id.rl_bottom_view);
        tv_dialog_success_content = (TextView) findViewById(R.id.tv_dialog_success_content);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_phone.setOnClickListener(this);
        tv_banlce = (TextView) findViewById(R.id.tv_banlce);
        tv_gold = (TextView) findViewById(R.id.tv_gold);
        tv_ban = (TextView) findViewById(R.id.tv_ban);
        tv_free = (TextView) findViewById(R.id.tv_free);
        tv_Illegal = (TextView) findViewById(R.id.tv_Illegal);
        cancel = (TextView) findViewById(R.id.cancel);

        tv_thaw = (TextView) findViewById(R.id.tv_thaw);
        tv_thaw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!MoneyUtil.moneyBigThan(cash_froze, "0")) {
                    showToast("无需解冻");
                } else {
                    netRequest.requestStoresUnfreezeBalanceForConsumer(6, consumerId);
                }
            }
        });
        rl_view = (RelativeLayout) findViewById(R.id.rl_view);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rl_view.setVisibility(View.GONE);
                handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 0);
            }
        });
        iv_duijiangma = (ImageView) findViewById(R.id.iv_duijiangma);
        tv_duijiangma = (TextView) findViewById(R.id.tv_duijiangma);
        ll_duijiangma = (LinearLayout) findViewById(R.id.ll_duijiangma);
        ll_duijiangma.setOnClickListener(this);
        tv_luck_number = (TextView) findViewById(R.id.tv_luck_number);
        tv_get_reward = (TextView) findViewById(R.id.tv_get_reward);
        tv_duijiangma_ok = (TextView) findViewById(R.id.tv_duijiangma_ok);
        tv_duijiangma_ok.setOnClickListener(this);
        rl_duijiang_success = (RelativeLayout) findViewById(R.id.rl_duijiang_success);
        tv_duijiang_fail_why = (TextView) findViewById(R.id.tv_duijiang_fail_why);
        tv_duijiang_fail_ok = (TextView) findViewById(R.id.tv_duijiang_fail_ok);
        rl_duijiang_dialog_fail = (RelativeLayout) findViewById(R.id.rl_duijiang_dialog_fail);
        tv_duijiang_fail_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rl_duijiang_dialog_fail.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_family_card:
                currentState = STATE_FAMILY_CARD;
                tv_family_card.setTextColor(getResources().getColor(R.color.orange1));
                tv_scan_pay.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                iv_member.setBackgroundResource(R.drawable.saohuima);
                tv_member.setTextColor(getResources().getColor(R.color.text_color_capture_gray));

                tv_validate_coupon.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                img_family_card.setBackgroundResource(R.drawable.capture_family_card_check);
                img_scan_pay.setBackgroundResource(R.drawable.capture_scan_pay_check);
                img_validate_coupon.setBackgroundResource(R.drawable.capture_coupon_check);

                tv_duijiangma.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                iv_duijiangma.setBackgroundResource(R.drawable.duijiangma_no_choose);
                break;
            case R.id.ll_scan_pay:
                currentState = STATE_SCAN_PAY;
                tv_family_card.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                iv_member.setBackgroundResource(R.drawable.saohuima);
                tv_member.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                tv_scan_pay.setTextColor(getResources().getColor(R.color.orange1));
                tv_validate_coupon.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                img_family_card.setBackgroundResource(R.drawable.capture_family_card1);
                img_scan_pay.setBackgroundResource(R.drawable.capture_scan_pay);
                img_validate_coupon.setBackgroundResource(R.drawable.capture_coupon_check);
                tv_duijiangma.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                iv_duijiangma.setBackgroundResource(R.drawable.duijiangma_no_choose);
                break;
            case R.id.ll_member:
                currentState = STATE_MEMEBER_PAY;
                tv_family_card.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                iv_member.setBackgroundResource(R.drawable.red_saohuima);
                tv_member.setTextColor(getResources().getColor(R.color.orange1));
                tv_scan_pay.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                tv_validate_coupon.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                img_family_card.setBackgroundResource(R.drawable.capture_family_card1);
                img_scan_pay.setBackgroundResource(R.drawable.capture_scan_pay_check);
                img_validate_coupon.setBackgroundResource(R.drawable.capture_coupon_check);
                tv_duijiangma.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                iv_duijiangma.setBackgroundResource(R.drawable.duijiangma_no_choose);
                break;
            case R.id.ll_validate_coupon:
                currentState = STATE_VALIDATE_COUPON;
                iv_member.setBackgroundResource(R.drawable.saohuima);
                img_family_card.setBackgroundResource(R.drawable.capture_family_card1);
                img_scan_pay.setBackgroundResource(R.drawable.capture_scan_pay_check);
                img_validate_coupon.setBackgroundResource(R.drawable.capture_coupon);
                tv_member.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                tv_family_card.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                tv_scan_pay.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                tv_validate_coupon.setTextColor(getResources().getColor(R.color.orange1));
                tv_duijiangma.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                iv_duijiangma.setBackgroundResource(R.drawable.duijiangma_no_choose);

                break;
            //兑奖码
            case R.id.ll_duijiangma:
                currentState = STATE_DUIJIANGMA;
                iv_duijiangma.setBackgroundResource(R.drawable.saohuima);
                tv_member.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                tv_family_card.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                tv_scan_pay.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                tv_validate_coupon.setTextColor(getResources().getColor(R.color.text_color_capture_gray));
                img_family_card.setBackgroundResource(R.drawable.capture_family_card1);
                img_scan_pay.setBackgroundResource(R.drawable.capture_scan_pay_check);
                img_validate_coupon.setBackgroundResource(R.drawable.capture_coupon_check);
                tv_duijiangma.setTextColor(getResources().getColor(R.color.orange1));
                iv_duijiangma.setBackgroundResource(R.drawable.duijiangma_choose);
                break;


            case R.id.tv_fail_ok:
                rl_dialog_fail.setVisibility(View.GONE);
                setReCapture();
                break;
            case R.id.tv_success_ok:
                rl_dialog_success.setVisibility(View.GONE);
                setReCapture();
                break;
            //兑奖码弹窗中的我知道了
            case R.id.tv_duijiangma_ok:
                rl_duijiang_success.setVisibility(View.GONE);
                setReCapture();
                break;
        }
    }

    @Override
    public void onAfinalFail() {
        showToast("请检查本地网络！");
        dismissProgressDialog();
        handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 1000);
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        dismissProgressDialog();
        if (requestId == 1) {
//            EventBus.getDefault().post(new CouponUpdateBean(2));
            tv_dialog_success_content.setText("验证成功");
            rl_dialog_success.setVisibility(View.VISIBLE);
        } else if (requestId == 5) {
            showToast("亲情卡支付成功");
            Log.v("zyl", "扫描亲情卡支付成功");
            handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 5000);
            //收银记录
            new commit_record().start();
        } else if (requestId == 3) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                String cash_balance = jsonObject.getString("cash_balance");
                String gold = jsonObject.getString("gold");
                String total_num = jsonObject.getString("total_num");
                String violation_num = jsonObject.getString("violation_num");
                String mobile = jsonObject.getString("mobile");
                cash_froze = jsonObject.getString("cash_froze");

                tv_ban.setText(cash_froze);
                tv_phone.setText(mobile);
                tv_banlce.setText(cash_balance);
                tv_gold.setText(gold);
                tv_free.setText(total_num);
                tv_Illegal.setText(violation_num);
                Log.v("zyl", "解冻金额：" + cash_froze);
                rl_view.setVisibility(View.VISIBLE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestId == 6) {
            rl_view.setVisibility(View.GONE);
            handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 0);
            showToast("解冻成功");
        }
        //验证中奖二维码成功
        else if (requestId == 7) {
            String title = "";//标题
            String award_name = "";//商品名称
            String luck_code = "";//幸运号码
            try {
                JSONObject jsonObject = new JSONObject(result);
                title = jsonObject.getString("title");
                award_name = jsonObject.getString("award_name");//商品名称
                luck_code = jsonObject.getString("luck_code");
            } catch (Exception e) {

            }
            String content = "奖品:" + award_name;
            if (!TextUtils.isEmpty(content)) {
                tv_get_reward.setText(content);
            }
            rl_duijiang_success.setVisibility(View.VISIBLE);
        }
        //查询优惠券信息成功
        else if(requestId == 8){
            try {
                JSONObject jsonObject = new JSONObject(result);
                final String status = jsonObject.getString("status");
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                dialogBuilder.create();
                LayoutInflater inflater = LayoutInflater.from(this);
                View temp = inflater.inflate(R.layout.dialog_youhuiquan, null);
                TextView tv_ok = (TextView) temp.findViewById(R.id.tv_ok);
                TextView tv_cancel = (TextView) temp.findViewById(R.id.tv_cancel);
                tv_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!TextUtils.isEmpty(MainActivity.member_id) && !TextUtils.isEmpty(sktCode)) {
                            dialog.dismiss();
                            //如果是这种状态 说明验证过了
                            if (status.equals("verified")) {
                                tv_dialog_success_content.setText("无需验证");
                                rl_dialog_success.setVisibility(View.VISIBLE);
                            } else {
                                netRequest.requestCouponValidate(7, sktCode);
                            }
                        }
                    }
                });
                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.setView(temp);
                dialog = dialogBuilder.show();
            } catch (Exception e) {

            }
        }
        //查询抽奖信息成功
        else if(requestId == 9){
            try {
                JSONObject jsonObject = new JSONObject(result);
                final String activity_type_after = jsonObject.getString("activity_type");
                String award_name = jsonObject.getString("award_name");
                String award_pic_path1_url = jsonObject.getString("award_pic_path1_url");
                String created_date = jsonObject.getString("created_date");
                String title = jsonObject.getString("title");
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                dialogBuilder.create();
                LayoutInflater inflater = LayoutInflater.from(this);
                View temp = inflater.inflate(R.layout.dialog_duijiangma, null);
                TextView tv_ok = (TextView) temp.findViewById(R.id.tv_ok);
                TextView tv_cancel = (TextView) temp.findViewById(R.id.tv_cancel);
                TextView tv_activity_name = (TextView) temp.findViewById(R.id.tv_activity_name);
                TextView tv_activity_type = (TextView) temp.findViewById(R.id.tv_activity_type);
                TextView tv_time = (TextView) temp.findViewById(R.id.tv_time);
                TextView tv_title = (TextView) temp.findViewById(R.id.tv_title);
                ImageView iv = (ImageView) temp.findViewById(R.id.iv);
                String tempName = activity_type_after;
                if (tv_activity_type.equals("YYY")) {
                    tempName = "摇一摇";
                } else if (tv_activity_type.equals("GGL")) {
                    tempName = "刮刮乐";
                } else if (tv_activity_type.equals("DSK")) {
                    tempName = "定时开";
                }
                tv_activity_name.setText(award_name);
                tv_activity_type.setText(tempName);
                tv_time.setText(created_date);
                tv_title.setText(title);
                ImageLoader.getInstance().displayImage(award_pic_path1_url, iv, options);
                tv_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!TextUtils.isEmpty(MainActivity.member_id) && !TextUtils.isEmpty(activity_id) && !TextUtils.isEmpty(consumer_id) && !TextUtils.isEmpty(draw_code) && !TextUtils.isEmpty(activity_type_after) && !TextUtils.isEmpty(process_id)) {
                            dialog.dismiss();
                            netRequest.requestValidateCode(7, MainActivity.member_id, activity_id, consumer_id, draw_code, activity_type_after, process_id);
                        }
                    }
                });
                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.setView(temp);
                dialog = dialogBuilder.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(requestId == 2){
            try {
                JSONObject jsonObject = new JSONObject(result);
                final String status = jsonObject.getString("status");
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                dialogBuilder.create();
                LayoutInflater inflater = LayoutInflater.from(this);
                View temp = inflater.inflate(R.layout.dialog_youhuiquan, null);
                TextView tv_ok = (TextView) temp.findViewById(R.id.tv_ok);
                TextView tv_cancel = (TextView) temp.findViewById(R.id.tv_cancel);
                tv_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!TextUtils.isEmpty(MainActivity.member_id) && !TextUtils.isEmpty(sktCode)) {
                            dialog.dismiss();
                            //如果是这种状态 说明验证过了
                            if (status.equals("verified")) {
                                tv_dialog_success_content.setText("无需验证");
                                rl_dialog_success.setVisibility(View.VISIBLE);
                            } else {
                                netRequest.requestCouponValidate(1, sktCode);
                            }
                        }
                    }
                });
                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.setView(temp);
                dialog = dialogBuilder.show();
            } catch (Exception e) {

            }
        }

    }
    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .showImageOnLoading(R.drawable.default_picture_s)
            .showImageOnFail(R.drawable.default_picture_s)
            .showStubImage(R.drawable.default_picture_s)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();
    @Override
    public void onExecuteFail(int requestId, String msg) {
        dismissProgressDialog();
        if (requestId == 1) {
            rl_dialog_fail.setVisibility(View.VISIBLE);
        } else if (requestId == 5) {
            showToast(msg);
            Log.v("zyl", "扫描亲情卡支付失败");
            handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 3000);
        } else if (requestId == 3) {
            showToast(msg);
            handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 3000);
        } else if (requestId == 6) {
            showToast(msg);
        } else if (requestId == 7) {
            if(!TextUtils.isEmpty(msg)){
                tv_duijiang_fail_why.setText(msg);
            }else{
                tv_duijiang_fail_why.setText("验证失败");
            }
            rl_duijiang_dialog_fail.setVisibility(View.VISIBLE);
            handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 3000);
        }else{
            showToast(msg);
        }
    }

    //6.18	扫描亲情卡获取会员信息
    public class access_member extends Thread {
        private String card_number;

        public access_member(String card_number) {
            this.card_number = card_number;
        }

        public void run() {
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("app_token", MainActivity.app_token));
                JSONObject paramsone = new JSONObject();
                paramsone.put("card_no", card_number);
                params.add(new BasicNameValuePair("params", paramsone.toString()));
                params.add(new BasicNameValuePair("service", "finance.consumerPrepayCardScan"));
                String sign = Submit.genPackageSign(params);
                params.add(new BasicNameValuePair("sign", sign));
                JSONObject obj = Submit.submit(params, Stores.http + "/openapi/finance");
                String rsp_code = obj.getString("rsp_code");
                if (rsp_code.equals("succ")) {

                    JSONObject data = obj.getJSONObject("data");
                    Log.v("zyl", "会员信息获取成功：" + data.toString());
                    member_id = data.getString("member_id");
                    //亲情卡余额
                    cash_balance = data.getString("cash_balance");
                    try {
                        nick_name = data.getString("nick_name");
                    } catch (Exception e) {
                        e.printStackTrace();
                        nick_name = "暂无昵称";
                    }
                    voucher_balance = data.getString("voucher_balance");
                    gold = data.getString("gold");

                    if (ifcashier == 2) {
                        //扫一扫进入的
                        handler.sendEmptyMessage(MSG_QINGQINGKA_SUCC);
                    } else {
                        handler.sendEmptyMessage(MSG_QINGQINGKA_MEMBER_SUCC);
                    }

                } else {
                    if (goToLogin.setGoToLogin(obj)) {

                    } else {

                        Message message = new Message();
                        message.obj = obj.getString("error_msg");
                        message.what = MSG_GETMENBER_FAILED;
//                    handler.sendEmptyMessage(MSG_GETMENBER_FAILED);
                        handler.sendMessage(message);
                        Log.v("zyl", "查询会员信息失败：" + obj.getString("error_msg"));
                    }
                }
                /*
                default:
					pay_password = "";
					error = (String) obj.get("error");
					offline.play(error);
					if (error.equals("请输入支付密码")) {
						handler.sendEmptyMessage(9);
						break;
					}
					handler.sendEmptyMessage(8);
					break;
				}*/

            } catch (Exception e) {
                Log.v("zyl", "会员信息获取失败,网络不通");
                handler.sendEmptyMessage(MSG_NETWORK_FAILED);
            }

        }
    }

    //订单支付
    public class consume extends Thread {
        private String member_id;
        private double money;

        public consume(String member_id, double money) {
            this.member_id = member_id;
            this.money = money;
        }

        public void run() {
            /*if (!pay_password.equals("")) {
                pay_password = md5(pay_password);
			}*/
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("user_token", MainActivity.user_token));
                JSONObject paramsone = new JSONObject();
                paramsone.put("data_source", "SJLY_02");
                tsLong = System.currentTimeMillis() / 1000;
                paramsone.put("transaction_date", time_String(tsLong));
                paramsone.put("detail", "亲情卡");
                paramsone.put("amount", money + "");
                paramsone.put("out_trade_no", IDUtil.getOutTradeNo());
                paramsone.put("payment_way_key", "ZFFS_05");
                paramsone.put("buyer_id", member_id);
                paramsone.put("seller_id", MainActivity.member_id);
                params.add(new BasicNameValuePair("params", paramsone.toString()));
                params.add(new BasicNameValuePair("service", "finance.orderPay"));
                String sign = Submit.genPackageSignUser(params);
                params.add(new BasicNameValuePair("sign", sign));
                JSONObject obj = Submit.submit(params, Stores.http + "/openapi/finance");
                String rsp_code = obj.getString("rsp_code");
                if (rsp_code.equals("succ")) {
                    Log.v("zyl", "扣款成功");
                    handler.sendEmptyMessage(MSG_KOUKUAN_SUCC);
                } else {
                    if (goToLogin.setGoToLogin(obj)) {

                    } else {
                        error = (String) obj.get("error_msg");
                        //显示刷卡失败
                        handler.sendEmptyMessage(MSG_KOUKUAN_FAILED);
                    }
                }
            } catch (Exception e) {
                ///333333333
                handler.sendEmptyMessage(MSG_NETWORK_FAILED);
            }

        }
    }

    /**
     * 二维码是否有效
     */
    public class Trading_check extends Thread {
        JSONObject object;

        public Trading_check(JSONObject object) {
            this.object = object;
        }

        public void run() {
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("app_token", MainActivity.app_token));
                params.add(new BasicNameValuePair("flow_no", object.getString("flow_no")));
                params.add(new BasicNameValuePair("security_code", object.getString("security_code")));
                String sign = Submit.genPackageSign(params);
                params.add(new BasicNameValuePair("sign", sign));
                JSONObject obj = Submit.submit(params, Stores.http + "/openapi/trade/verify");
                Log.v("zyl", "验证二维码：" + obj.toString());
                String rsp_code = obj.getString("rsp_code");
                if (rsp_code.equals("succ")) {

                    handler.sendEmptyMessage(12);

                } else {
                    if (goToLogin.setGoToLogin(obj)) {

                    } else {
                        error = "二维码已失效";
                        handler.sendEmptyMessage(4);
                        handler.sendEmptyMessageDelayed(MSG_RE_SCAN, 3000);
                    }
                }
            } catch (Exception e) {
                handler.sendEmptyMessage(MSG_NETWORK_FAILED);
            }

        }
    }

    public class proceeds extends Thread {
        JSONObject object;

        public proceeds(JSONObject object) {
            this.object = object;
        }

        public void run() {
            try {
                Log.v("zyl", "object:" + object);
                JSONObject params = new JSONObject();
                params.put("data_source", "SJLY_02");
                tsLong = System.currentTimeMillis() / 1000;
                //params.put("transaction_date",time_String(tsLong));
                params.put("pid", MainActivity.member_id);
                String s_voucher = null;
                try {
                    s_voucher = object.getString("voucher");
                } catch (Exception e) {

                }
                if (TextUtils.isEmpty(s_voucher)) {
                    params.put("detail", "扫码支付");
                } else {
                    params.put("detail", "零钱");
                }

                params.put("payment_way_key", "ZFFS_05");
                params.put("amount", object.get("amount") + "");
                params.put("buyer_id", object.get("member_id") + "");
                params.put("seller_id", MainActivity.member_id);
                try {
                    String s_flow_no = object.getString("flow_no");
                    if (!TextUtils.isEmpty(s_flow_no)) {
                        params.put("out_trade_no", s_flow_no);
                    }
                } catch (Exception e) {

                }
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("buyer_id", object.get("member_id") + "");
                jsonObject2.put("seller_id", MainActivity.member_id);
                jsonObject2.put("security_code", object.get("security_code") + "");
                jsonObject2.put("security_code_type", "P");//代表二维码是付款码


                params.put("out_trade_body", jsonObject2.toString());
                List<NameValuePair> paramsone = new ArrayList<NameValuePair>();
                paramsone.add(new BasicNameValuePair("params", params.toString()));
                paramsone.add(new BasicNameValuePair("service", "finance.balancePay"));
                paramsone.add(new BasicNameValuePair("user_token", MainActivity.user_token));
                String sign = Submit.genPackageSignUser(paramsone);
                paramsone.add(new BasicNameValuePair("sign", sign));
                JSONObject obj = Submit.submit(paramsone, Stores.http + "/openapi/finance");
                String rsp_code = obj.getString("rsp_code");
                Log.v("zyl", "交易接口:" + obj.toString());
                if (rsp_code.equals("succ")) {
                    //收款成功之后隐藏确认收款弹窗
                    handler.sendEmptyMessage(98);
//                    finish();
                } else {
                    if (goToLogin.setGoToLogin(obj)) {

                    } else {
                        error = (String) obj.get("error_msg");
                        handler.sendEmptyMessage(MSG_LIQUAN_FAILED);
                    }
                }
            } catch (Exception e) {
                //////1111
                handler.sendEmptyMessage(MSG_NETWORK_FAILED);
            }

        }
    }

    public void show_failure(View view) {
        // 一个自定义的布局，作为显示的内容
        final View contentView = LayoutInflater.from(context).inflate(
                R.layout.cash_register_finish, null);
        // 设置按钮的点击事件
        ImageView occlude = (ImageView) contentView.findViewById(R.id.occlude);
        occlude.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.v("zyl", "执行了关闭");
                handler.sendEmptyMessage(1);
            }
        });

        popupWindow = new PopupWindow(contentView, width - 100, LayoutParams.WRAP_CONTENT);
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.setTouchable(true);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        popupWindow.showAsDropDown(view, 50, 50);

    }

    /**
     * 礼券赠送
     */
    public class Presented extends Thread {


        public void run() {


            try {
                JSONObject params = new JSONObject();
                params.put("data_source", "SJLY_02");
                params.put("detail", "店东赠送");

                params.put("amount", token + "");
                params.put("out_trade_no", IDUtil.getOutTradeNo());
                params.put("payment_way_key", "ZFFS_06");
                params.put("buyer_id", member_id);
                params.put("seller_id", MainActivity.member_id);
                params.put("out_trade_body", params.toString());
                List<NameValuePair> paramsone = new ArrayList<NameValuePair>();
                paramsone.add(new BasicNameValuePair("app_token", MainActivity.app_token));
                paramsone.add(new BasicNameValuePair("params", params.toString()));
                paramsone.add(new BasicNameValuePair("service", "finance.orderReward"));
                String sign = Submit.genPackageSign(paramsone);
                paramsone.add(new BasicNameValuePair("sign", sign));

                JSONObject obj = Submit.submit(paramsone, Stores.http + "/openapi/finance");
                String rsp_code = obj.getString("rsp_code");
                if (rsp_code.equals("succ")) {
                    Log.v("zyl", "礼券赠送成功");
                    //更新礼券余额
                    Stores.voucher_balance = Stores.voucher_balance - token;
                    donate = 1;
                    handler.sendEmptyMessage(MSG_LIQUAN_SUCC);

                } else {
                    if (goToLogin.setGoToLogin(obj)) {

                    } else {
                        error = (String) obj.get("error_msg");
                        Log.v("zyl", "礼券赠送失败:" + error);
                        handler.sendEmptyMessage(MSG_LIQUAN_FAILED);
                    }
                }

            } catch (Exception e) {
                handler.sendEmptyMessage(MSG_NETWORK_FAILED);
            }

        }
    }

    /**
     * 生成收银记录
     */
    public class commit_record extends Thread {

        public void run() {
            try {
                JSONObject params = new JSONObject();
                params.put("flow_no", IDUtil.getOutTradeNo());
                params.put("stores_id", MainActivity.member_id);
                params.put("amount", money + "");
                params.put("discount_amount", number_of_credits + "");
                params.put("pay_amount", money);
                params.put("cashier_id", MainActivity.member_id);
                params.put("payment_way_key", "ZFFS_05");
                List<NameValuePair> paramsone = new ArrayList<NameValuePair>();
                paramsone.add(new BasicNameValuePair("app_token", MainActivity.app_token));
                paramsone.add(new BasicNameValuePair("params", params.toString()));
                paramsone.add(new BasicNameValuePair("service", "finance.storesCashierCreate"));
                String sign = Submit.genPackageSign(paramsone);
                paramsone.add(new BasicNameValuePair("sign", sign));

                JSONObject obj = Submit.submit(paramsone, Stores.http + "/openapi/finance");
                String rsp_code = obj.getString("rsp_code");
                if (rsp_code.equals("succ")) {
                    achieve = 1;
                    handler.sendEmptyMessage(MSG_LIQUAN_SUCC);
                    Log.v("zyl", "生成收银记录成功");

                } else {
                    if (goToLogin.setGoToLogin(obj)) {

                    } else {
                        error = (String) obj.get("error_msg");
                        handler.sendEmptyMessage(MSG_LIQUAN_FAILED);
                        Log.v("zyl", "生成收银记录失败：" + error);
                    }
                }

            } catch (Exception e) {
                handler.sendEmptyMessage(MSG_NETWORK_FAILED);
            }

        }
    }

    public String time_String(long first_time) {
        Date date = new Date(first_time * 1000);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        return dateString;
    }
}
